package com.yf.springboot.config;

import com.yf.springboot.mapper.CronMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 动态定时任务配置类
 *
 * @author yvan
 **/
// @Configuration      //1.主要用于标记配置类，兼备Component的效果
// @EnableScheduling   //2.开启定时任务
public class DynamicScheduleConfigurer implements SchedulingConfigurer {
    // 注入mapper
    @Resource
    private CronMapper cronMapper;

    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        System.out.println("taskRegistrar: " + taskRegistrar);
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(5);
        taskScheduler.initialize();
        taskRegistrar.setTaskScheduler(taskScheduler);
        taskRegistrar.addTriggerTask(
            // 1.添加任务内容(Runnable)
            () -> System.out.println("欢迎访问 pan_junbiao的博客: " + LocalDateTime.now().toLocalTime()),
            // 2.设置执行周期(Trigger)
            triggerContext -> {
                // 2.1 从数据库获取执行周期
                String cron = cronMapper.getCron();
                // 2.2 合法性校验.
                if (StringUtils.hasLength(cron)) {
                    // Omitted Code ..
                }
                // 2.3 返回执行周期(Date)
                return new CronTrigger(cron).nextExecutionTime(triggerContext);
            }
        );
    }
}
